<template>
  <div id="editor" ref="editor"></div>
</template>

<script>
import Editor from 'wangeditor'
import {
  verifyHtml
} from '@/utils/verifiable'
import modal from '@/utils/modal'
export default {
  name: 'YlEditor',
  data () {
    return {
      editor: '',
      token: '',
      txt: '',
      initTxt: '<h1><br>富文本标题</h1><p><img src="https://timgsa.baidu.com/timg?image&amp;quality=80&amp;size=b9999_10000&amp;sec=1585138112648&amp;di=4ee45f6dfe62cef0ce5e7b6c7227dafd&amp;imgtype=0&amp;src=http%3A%2F%2Fa2.att.hudong.com%2F54%2F49%2F01300542446111139563495498728.jpg"><br></p><p>测试数据12345657788</p><p>正文lalalalal</p>'
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.createEditor()
    })
  },
  methods: {
    createEditor () {
      let _this = this

      this.editor = new Editor('#editor')
      // 资源服务器地址
      // this.editor.custiomConfig.uploadImgServer = ''

      // 允许跨域
      this.editor.customConfig.withCredentials = true

      // Token
      this.editor.customConfig.uploadImgHeaders = {}

      // 文件名
      this.editor.customConfig.uploadFileName = 'file'

      // 上传图片
      this.editor.customConfig.uploadImgHooks = {
        customInsert: (insertImg, result, editor) => {
          console.log(result)
          // 设置图片上传地址 回显图片
          // const URL = ''
          insertImg(URL)
        }
      }

      // 菜单设置
      this.editorMenu()

      // 颜色设置
      this.editorColor()

      // 字体设置
      this.editorFont()

      // 创建editor编辑器
      this.editor.create()

      this.editor.change = function () {
        _this.$emit('getHtml', this.txt.html())
      }
    },

    // 菜单
    editorMenu () {
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'emoticon', // 表情
        'image', // 插入图片
        'table', // 表格
        'code', // 插入代码
        'undo', // 撤销
        'redo' // 重复
      ]
    },

    // 颜色
    editorColor () {
      this.editor.customConfig.colors = [
        '#000000',
        '#eeece0',
        '#1c487f',
        '#4d80bf',
        '#c24f4a',
        '#8baa4a',
        '#7b5ba1',
        '#46acc8',
        '#f9963b',
        '#ffffff'
      ]
    },

    // 字体设置
    editorFont () {
      this.editor.customConfig.fontNames = [
        '宋体',
        '微软雅黑',
        'Arial',
        'Tahoma',
        'Verdana'
      ]
    },

    checkFontSize (txt) {
      if (txt.length < 1) {
        modal.warning(this, '字数过少')
        return false
      } else {
        return txt
      }
    },

    setHtml (txt = this.initTxt) {
      verifyHtml(txt) ? this.editor.txt.html(txt) : this.editor.txt.text(txt)
    },

    getHtml () {
      return this.editor.txt.html()
    }
  }
}
</script>
